package com.sts.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sts.dto.NotificationCreateDTO;
import com.sts.dto.NotificationDTO;
import com.sts.entity.Notification;
import com.sts.mapper.NotificationMapper;
import com.sts.service.NotificationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class NotificationServiceImpl implements NotificationService {

    private final NotificationMapper notificationMapper;

    @Override
    public Long create(NotificationCreateDTO dto) {
        Notification entity = Notification.builder()
                .receiverId(dto.getReceiverId())
                .type(dto.getType())
                .title(dto.getTitle())
                .content(dto.getContent())
                .isRead(false)
                .extra(dto.getExtra())
                .createdAt(LocalDateTime.now())
                .build();
        notificationMapper.insert(entity);
        return entity.getId();
    }

    @Override
    public List<NotificationDTO> listUnread(Long receiverId) {
        LambdaQueryWrapper<Notification> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Notification::getReceiverId, receiverId)
                .eq(Notification::getIsRead, false)
                .orderByDesc(Notification::getCreatedAt);
        return notificationMapper.selectList(wrapper)
                .stream().map(e -> BeanUtil.copyProperties(e, NotificationDTO.class))
                .collect(Collectors.toList());
    }

    @Override
    public List<NotificationDTO> listAll(Long receiverId) {
        LambdaQueryWrapper<Notification> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Notification::getReceiverId, receiverId)
                .orderByDesc(Notification::getCreatedAt);
        return notificationMapper.selectList(wrapper)
                .stream().map(e -> BeanUtil.copyProperties(e, NotificationDTO.class))
                .collect(Collectors.toList());
    }

    @Override
    public void markRead(Long notificationId, Long receiverId) {
        LambdaUpdateWrapper<Notification> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Notification::getIsRead, true)
                .eq(Notification::getId, notificationId)
                .eq(Notification::getReceiverId, receiverId);
        notificationMapper.update(null, wrapper);
    }

    @Override
    public void markAllRead(Long receiverId) {
        LambdaUpdateWrapper<Notification> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Notification::getIsRead, true)
                .eq(Notification::getReceiverId, receiverId);
        notificationMapper.update(null, wrapper);
    }
}